﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using System.Reflection;
using eTerm.PlugIn.NCore;
using eTerm.MsSql.DbProvider;

namespace eTerm.DETR.StandAloneVersion
{
    public partial class frmSetting : Form
    {
        string AssemblyPath =string.Empty;// Path.GetDirectoryName(this.GetType().Assembly.Location);
        string SetupXmlFile = @"AutoDETRPlugIn.xml";
        protected XElement XmlRoot = null;
        protected MailServerInfo mailModel = new MailServerInfo();
        protected Frequency ExecuteFrequency = new Frequency();
        protected eTermSocketSetup socketSetup = new eTermSocketSetup();
        public frmSetting()
        {
            InitializeComponent();
            this.Load += (o, e) => {
                AssemblyPath = Path.GetDirectoryName(this.GetType().Assembly.Location);
                SetupXmlFile = @"AutoDETRPlugIn.xml";
                string SetupFileName = Path.Combine(AssemblyPath, SetupXmlFile);
                if (!File.Exists(SetupFileName)) return;
                XmlRoot = XElement.Load(SetupFileName);
                ReadConnectSetup();
                ReadMailInfo();
            };
        }


        /// <summary>
        /// 设置Xml配置节点值.
        /// </summary>
        /// <param name="XmlNodeName">节点名称.</param>
        /// <param name="NodeValue">节点值.</param>
        protected virtual void SetElementValue(string XmlNodeName, string NodeValue)
        {
            string SetupFileName = Path.Combine(AssemblyPath, SetupXmlFile);
            try
            {
                XElement Node = XmlRoot.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == XmlNodeName.ToLower());
                if (Node != null)
                    Node.Value = NodeValue;
                else
                {
                    XmlRoot.Add(new XElement(XmlNodeName, NodeValue));
                }
                XmlRoot.Save(SetupFileName);
            }
            catch { }
        }

        /// <summary>
        /// 获取Xml配置节点值.
        /// </summary>
        /// <param name="XmlNodeName">节点名称.</param>
        /// <returns>System.String.</returns>
        protected virtual string GetElementValue(string XmlNodeName)
        {
            string Result = string.Empty;
            try
            {
                Result = XmlRoot.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == XmlNodeName.ToLower()).Value;
            }
            catch { }
            return Result;
        }


        private void ReadConnectSetup() {
            socketSetup = SetEntity<eTermSocketSetup>(@"SocketSetup");
            tbServer.Text = socketSetup.Server;
            tbUserName.Text = socketSetup.UserName;
            tbPassword.Text = socketSetup.Password;

            numPort.Value = socketSetup.Port;
            numRID.Value = socketSetup.RID;
            numSID.Value = socketSetup.SID;
            chkSSL.Checked = socketSetup.IsSSL;
        }

        private void ReadMailInfo() {
            mailModel = SetEntity<MailServerInfo>(@"MailServerInfo");
            ExecuteFrequency = SetEntity<Frequency>(@"Frequency");
            tbEmailServer.Text = mailModel.Server;
            tbEmailUser.Text = mailModel.UserName;
            tbUserPass.Text = mailModel.Password;
            numEmailPort.Value = mailModel.Port;

            SysUser userModel= SysUser.All().FirstOrDefault();
            tbReceiverName.Text = userModel.DisplayName;
            tbReceiverEmail.Text = userModel.Email;

            numFrequency.Value = ExecuteFrequency.OccursEveryMinutes;
        }



        /// <summary>
        /// 从Xml加载实体.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="XElementName">Name of the X element.</param>
        /// <returns>``0.</returns>
        protected T SetEntity<T>(string XElementName) where T : new()
        {
            T result = new T();
            try
            {
                XElement XElementNode = XmlRoot.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == XElementName.ToLower());
                if (XElementNode == null) return default(T);
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    XElement Node = XElementNode.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == property.Name.ToLower());
                    if (Node == null) continue;
                    try
                    {
                        property.SetValue(result, Convert.ChangeType(Node.Value, property.PropertyType), null);
                    }
                    catch
                    {
                        //FireOnNotify(property.Name, EventType.ERROR, string.Format(@"对像 {0} 属性 {1} 读取失败", typeof(T).Name, property.Name));
                    }
                }
            }
            catch (Exception ex)
            {
                //FireOnNotify(ex.GetType().Name, EventType.ERROR, ex.Message);
            }
            return result;
        }


        protected void UpdateEntity<T>(string XElementName,T model) where T : class, new() {
            try
            {
                XElement XElementNode = XmlRoot.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == XElementName.ToLower());
                if (XElementNode == null) return;
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    XElement Node = XElementNode.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == property.Name.ToLower());
                    if (Node == null) continue;
                    try
                    {
                        object v= Convert.ChangeType(property.GetValue(model, null), property.PropertyType);
                        XElement node = XElementNode.Elements().FirstOrDefault(l => l.Name.LocalName.ToLower() == property.Name.ToLower());
                        if (node == null) continue;
                        node.Value = v.ToString();
                    }
                    catch
                    {
                        //FireOnNotify(property.Name, EventType.ERROR, string.Format(@"对像 {0} 属性 {1} 读取失败", typeof(T).Name, property.Name));
                    }
                }
            }
            catch (Exception ex)
            {
                //FireOnNotify(ex.GetType().Name, EventType.ERROR, ex.Message);
            }


            string SetupFileName = Path.Combine(AssemblyPath, SetupXmlFile);
            try
            {
                XmlRoot.Save(SetupFileName);
            }
            catch { }

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            mailModel.Password = tbUserPass.Text.Trim();
            mailModel.Port =int.Parse( numEmailPort.Value.ToString());
            mailModel.Server = tbEmailServer.Text.Trim();
            mailModel.UserName = tbEmailUser.Text.Trim();
            UpdateEntity<MailServerInfo>(@"MailServerInfo",mailModel);

            SysUser uModel = SysUser.All().FirstOrDefault();
            uModel.DisplayName = tbReceiverName.Text.Trim();
            uModel.Email = tbReceiverEmail.Text.Trim();
            uModel.Save();


            ExecuteFrequency.OccursEveryMinutes = int.Parse(numFrequency.Value.ToString());
        }

    }
}
